package com.h5lib.nchuoffice;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.regex.Pattern;

public class NetUtil {

    private static final Pattern IPV4_PATTERN =  Pattern.compile("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
    
    public static void setProxy(String host, String port) {
        System.setProperty("proxySet", "true");  
        System.setProperty("proxyHost", host);
        System.setProperty("proxyPort", port);
    } 
    
    public static byte[] getLocalHostIp()
    {
        try
        {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements())
            {
                NetworkInterface networkInterface = en.nextElement();//得到每一个网络接口绑定的所有ip
                Enumeration<InetAddress> inet = networkInterface.getInetAddresses();
                while (inet.hasMoreElements())
                {
                    InetAddress ip = inet.nextElement();
                    if (!ip.isLoopbackAddress() && isIPv4Address(ip.getHostAddress()))
                    {
                    	return ip.getAddress();
                    }
                }

            }
        }
        catch (SocketException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public static boolean isIPv4Address(final String input) {
        return IPV4_PATTERN.matcher(input).matches();
    }
    
    public static boolean internalIp(){
    	return internalIp(getLocalHostIp());
    	
    }
    
    public static boolean internalIp(byte[] addr) {
    	if(addr == null){	
    		return false;
    	}
        final byte b0 = addr[0];
        final byte b1 = addr[1];
        //10.x.x.x/8
        final byte SECTION_1 = 0x0A;
        //172.16.x.x/12
        final byte SECTION_2 = (byte) 0xAC;
        final byte SECTION_3 = (byte) 0x10;
        final byte SECTION_4 = (byte) 0x1F;
        //192.168.x.x/16
        final byte SECTION_5 = (byte) 0xC0;
        final byte SECTION_6 = (byte) 0xA8;
        switch (b0) {
            case SECTION_1:
                return true;
            case SECTION_2:
                if (b1 >= SECTION_3 && b1 <= SECTION_4) {
                    return true;
                }
            case SECTION_5:
                switch (b1) {
                    case SECTION_6:
                        return true;
                }
            default:
                return false;
        }
    }
}
